package me.flyray.auth.util;

import java.io.ByteArrayOutputStream;
import java.security.Key;
import java.security.KeyFactory;
import java.security.PrivateKey;
import java.security.PublicKey;
import java.security.Signature;
import java.security.spec.PKCS8EncodedKeySpec;
import java.security.spec.X509EncodedKeySpec;

import javax.crypto.Cipher;

import me.flyray.common.util.Base64Utils;

/**
 * RSA公钥/私钥/签名工具包 字符串格式的密钥在未在特殊说明情况下都为BASE64编码格式
 * 由于非对称加密速度极其缓慢，一般文件不使用它来加密而是使用对称加密， 非对称加密算法可以用来对对称加密的密钥加密，这样保证密钥的安全也就保证了数据的安全
 */
public class RSAUtils {

	private static final String KEY_ALGORITHM = "RSA";
	public static final String X509 = "X.509";

	/**
	 * 签名算法
	 */
	private static final String SIGNATURE_ALGORITHM = "MD5withRSA";

	private static final String DEFAULT_CHARSET = "UTF-8";

	public static final String KEY_ALGORITHM_2 = "RSA";
	// public static final String KEY_ALGORITHM_2 = "RSA";

	/**
	 * 获取公钥的key
	 */
	private static final String PUBLIC_KEY = "RSAPublicKey";

	/**
	 * 获取私钥的key
	 */
	private static final String PRIVATE_KEY = "RSAPrivateKey";

	/**
	 * RSA最大加密明文大小
	 */
	private static final int MAX_ENCRYPT_BLOCK = 117;

	/**
	 * RSA最大解密密文大小
	 */
	private static final int MAX_DECRYPT_BLOCK = 128;

	/**
	 * <p>
	 * 用私钥对信息生成数字签名
	 * </p>
	 * 
	 * @param content
	 *            已加密数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * 
	 * @return
	 * @throws Exception
	 */
	public static String sign(String content, String privateKey) {
		try {
			PKCS8EncodedKeySpec priPKCS8 = new PKCS8EncodedKeySpec(Base64Utils.decode(privateKey));
			KeyFactory keyf = KeyFactory.getInstance(KEY_ALGORITHM);
			PrivateKey priKey = keyf.generatePrivate(priPKCS8);

			Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);

			signature.initSign(priKey);
			signature.update(content.getBytes(DEFAULT_CHARSET));

			byte[] signed = signature.sign();

			return Base64Utils.encode(signed);
		} catch (Exception e) {
			e.printStackTrace();
		}

		return null;
	}

	/**
	 * 校验数字签名
	 * 
	 * @param content
	 *            已加密数据
	 * @param publicKey
	 *            公钥(BASE64编码)
	 * @param sign
	 *            数字签名
	 * 
	 * @return
	 * @throws Exception
	 * 
	 */
	public static boolean verify(String content, String publicKey, String sign) throws Exception {
		byte[] keyBytes = Base64Utils.decode(publicKey);
		X509EncodedKeySpec keySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PublicKey publicK = keyFactory.generatePublic(keySpec);
		Signature signature = Signature.getInstance(SIGNATURE_ALGORITHM);
		signature.initVerify(publicK);
		signature.update(content.getBytes(DEFAULT_CHARSET));
		return signature.verify(Base64Utils.decode(sign));
	}

	/*
	 * 把16进制字符串转换成字节数组
	 * 
	 * @param hex
	 * 
	 * @return
	 */
	public static byte[] hexStringToByte(String hexString) {
		if (hexString == null || hexString.equals("")) {
			return null;
		}
		hexString = hexString.toLowerCase();
		int length = hexString.length() / 2;
		char[] hexChars = hexString.toCharArray();
		byte[] d = new byte[length];
		for (int i = 0; i < length; i++) {
			int pos = i * 2;
			d[i] = (byte) (charToByte(hexChars[pos]) << 4 | charToByte(hexChars[pos + 1]));
		}
		return d;
	}

	/**
	 * 把字节数组转换成16进制字符串
	 * 
	 * @param src
	 * @return
	 */
	public static final String bytesToHexString(byte[] src) {
		StringBuilder stringBuilder = new StringBuilder("");
		if (src == null || src.length <= 0) {
			return null;
		}
		for (int i = 0; i < src.length; i++) {
			int v = src[i] & 0xFF;
			String hv = Integer.toHexString(v);
			if (hv.length() < 2) {
				stringBuilder.append(0);
			}
			stringBuilder.append(hv);
		}
		return stringBuilder.toString();
	}

	private static byte charToByte(char c) {
		return (byte) "0123456789abcdef".indexOf(c);
	}

	/**
	 * 移动端解密
	 * 
	 * @param encryptedData
	 *            已加密数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static byte[] decrypt(String encryptedData, String privateKey) throws Exception {
		// 转16进制
		byte[] hexData = hexStringToByte(encryptedData);
		byte[] keyBytes = Base64Utils.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		PrivateKey privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_2);
		cipher.init(Cipher.DECRYPT_MODE, privateK);
		byte[] decryptedData = cipher.doFinal(hexData);

		// 标志位为0之后的是输入的有效字节
		int i = decryptedData.length - 1;
		while (i > 0 && decryptedData[i] != 0) {
			i--;
		}
		if (i > 0)
			i++;
		byte[] data = new byte[decryptedData.length - i];
		for (int j = i; j < decryptedData.length; j++) {
			data[j - i] = decryptedData[j];
		}
		return data;
	}

	/**
	 * 私钥解密
	 * 
	 * @param encryptedData
	 *            已加密数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPrivateKey(byte[] encryptedData, String privateKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_2);
		cipher.init(Cipher.DECRYPT_MODE, privateK);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return decryptedData;
	}
	/**
	 * 私钥加密
	 * 
	 * @param data
	 *            源数据
	 * @param privateKey
	 *            私钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptByPrivateKey(byte[] data, String privateKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(privateKey);
		PKCS8EncodedKeySpec pkcs8KeySpec = new PKCS8EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance("MD5withRSA");
		Key privateK = keyFactory.generatePrivate(pkcs8KeySpec);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_2);
		cipher.init(Cipher.ENCRYPT_MODE, privateK);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}
	/**
	 * 公钥解密
	 * 
	 * @param encryptedData
	 *            已加密数据
	 * @param publicKey
	 *            公钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static byte[] decryptByPublicKey(byte[] encryptedData, String publicKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		Cipher cipher = Cipher.getInstance(KEY_ALGORITHM_2);
		cipher.init(Cipher.DECRYPT_MODE, publicK);
		int inputLen = encryptedData.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段解密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_DECRYPT_BLOCK) {
				cache = cipher.doFinal(encryptedData, offSet, MAX_DECRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(encryptedData, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_DECRYPT_BLOCK;
		}
		byte[] decryptedData = out.toByteArray();
		out.close();
		return decryptedData;
	}

	/**
	 * 公钥加密
	 * 
	 * @param data
	 *            源数据
	 * @param publicKey
	 *            公钥(BASE64编码)
	 * @return
	 * @throws Exception
	 */
	public static byte[] encryptByPublicKey(byte[] data, String publicKey) throws Exception {
		byte[] keyBytes = Base64Utils.decode(publicKey);
		X509EncodedKeySpec x509KeySpec = new X509EncodedKeySpec(keyBytes);
		KeyFactory keyFactory = KeyFactory.getInstance(KEY_ALGORITHM);
		Key publicK = keyFactory.generatePublic(x509KeySpec);
		// 对数据加密
		Cipher cipher = Cipher.getInstance(keyFactory.getAlgorithm());
		cipher.init(Cipher.ENCRYPT_MODE, publicK);
		int inputLen = data.length;
		ByteArrayOutputStream out = new ByteArrayOutputStream();
		int offSet = 0;
		byte[] cache;
		int i = 0;
		// 对数据分段加密
		while (inputLen - offSet > 0) {
			if (inputLen - offSet > MAX_ENCRYPT_BLOCK) {
				cache = cipher.doFinal(data, offSet, MAX_ENCRYPT_BLOCK);
			} else {
				cache = cipher.doFinal(data, offSet, inputLen - offSet);
			}
			out.write(cache, 0, cache.length);
			i++;
			offSet = i * MAX_ENCRYPT_BLOCK;
		}
		byte[] encryptedData = out.toByteArray();
		out.close();
		return encryptedData;
	}

	public static void main(String[] args) throws Exception {
		String publickey = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnUMv+c2ifPd6IGDNhDnsXGOxtLWsOWhWP9CTDj91nzvT1o/AnqoWzWAPsH/6uKxlc4nf5ot0QYM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RBgzH7XGr075t9Ri1lInOvm1UfvlbUvyySuxhexQKQ8jHjo583IiawXDre00WH/MlN8jC1M1PD7bdSSO5mtq9AVVo/YKwKrpJlnAgMBAAECgYBkV8h/qactGWXEKP9nTc/0YjYoo/x4dv5HfxwtTLJz92JhjxgQMexNSpPPoMCUo7RqSEe7pzj9AZCi4U5f/vTOMVLtDoGUQ0BXYSX+lw6XYO7ctAy6oAhsl9tFCii1Chk3HM0/VfgwQ72QZk7pTbzMosBRfMfcwKdF38PpTNmdwQJBAM/WCcQ2HtxRWLO7uYY41Fz1H4LnXC4txQcpqszSJw6up8fTz0RNL0JFopAJoCgy1tnp937kELc+Fq5YEWWwav0CQQDOFt1k8CLUS2Gz0XBz3jD0WTEQA2sXyAg9m47cXQP/lKFDnZDVUPYxHnHo1C0nZSFCeTT8b7q6CaHqw2hiVT0zAkAMNmyOfgukMJeAwDgvnelEqRa373ZoNEJOoHEr5fFrmHG9eUHFpq9vOn5J7nbdxdcAKRJk/2vICLr2dbBYBFzVAkEAiAFK5jwboCKHPdYv8idmAzuBR2IaIL2fwpiQNRkldFuv+SFY3Y3qiwvefJrZmbABvQ6kSxupDPEia/29O3epRQJBAMoI0DmrsVSErgCndgsr+fdoM0CizXTJ3pGOqVIQv5bqhA7NRUKnUjwoVpwu5ohKqdD9786RZU5ina8TrRhC6jE=
		String demo="W1wqdwesdfmok2";
		byte[] srtbyte=demo.getBytes("UTF-8");
		//byte[]encrypt=RSAUtils.encryptByPublicKey(srtbyte,publickey);
		//Rb5jPFiWolbtppRjnPY5GBiEA1T4eMP6TJS0NtFHSxBmPggM14pS6M6aZj+Y/fG9mia4pc02xYcqTlxE3VNr74lEZhgjAv4uGOjrUAo15ezHrO4alcv4iK6ao890pJkkkcz+WRWHYvcRSqrEnNjRYwtNSvMAZLO+baCaZgtiaEI=
		String encryptstr="Rb5jPFiWolbtppRjnPY5GBiEA1T4eMP6TJS0NtFHSxBmPggM14pS6M6aZj+Y/fG9mia4pc02xYcqTlxE3VNr74lEZhgjAv4uGOjrUAo15ezHrO4alcv4iK6ao890pJkkkcz+WRWHYvcRSqrEnNjRYwtNSvMAZLO+baCaZgtiaEI=";
		//String encryptstr= Base64Utils.encode(encrypt);
		System.out.println(encryptstr);
		byte[]encryptend =RSAUtils.decryptByPrivateKey(Base64Utils.decode(encryptstr),privatekey);
		String res = new String(encryptend,"UTF-8");
		System.out.println(res);
		
	}

}
